package br.com.felix.fwt.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import br.com.felix.fwt.security.exception.UnauthorizedAccessException;
import br.com.felix.fwt.servlet.FelixWebToolkitServlet;
import br.com.felix.fwt.servlet.FwtContext;
import br.com.felix.fwt.ui.Form;
import br.com.felix.fwt.ui.exception.ComponentRenderException;
import br.com.felix.fwt.ui.exception.UserInterfaceInitializationException;


/**
 * The Class InterfacePreview.
 */
public abstract class InterfacePreview {

	/** The output directory where the generated HTMLs will be created.
	 *  Must be set before calling generatePreview().
	 *  */
	public static String outputDirectory;
	
	public static String htmlOutputDirectory;
	
	/**
	 * Generates a preview of a form with a defined Style.
	 * 
	 * @param form the form that will be used to generate the preview.
	 * 
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws UserInterfaceInitializationException 
	 * @throws ComponentRenderException 
	 */
	public static void generatePreview(Class<? extends Form> clazz) throws IOException, UserInterfaceInitializationException, ComponentRenderException{
	    
	    Date start = new Date();
	    MockServletContext mockServletContext = new MockServletContext(outputDirectory);
	    MockHttpServletRequest request = new MockHttpServletRequest();
	    MockHttpServletResponse response = new MockHttpServletResponse();
	    MockHttpSession session = new MockHttpSession();
	    session.setServletContext(mockServletContext);
	    
	    request.setServletContext(mockServletContext);
	    request.setSession(session);
		FwtContext fwt = new FwtContext(request, response, null);
		FelixWebToolkitServlet.setFwtContext(fwt);
		Form form = null;
		try {
			form = clazz.newInstance();
		fwt.form = form;
			form.initializeForm();
		} 
		catch (InstantiationException e) {
			throw new UserInterfaceInitializationException(e);
		} 
		catch (IllegalAccessException e) {
			throw new UserInterfaceInitializationException(e);
		} 
		catch (UnauthorizedAccessException e) {
			throw new UserInterfaceInitializationException(e);
		}

		//form.initializeUserInterface();
		PrintWriter pw = response.getWriter();
		form.write(pw);
		pw.flush();
		pw.close();
		Date end = new Date();
		long diff = end.getTime() - start.getTime();
		System.out.println("Preview generated "+form.getClass().getCanonicalName()+".html in "+diff+" milliseconds.");
	}
}
